package com.cn.zsc.service;

import com.cn.zsc.db108.dao.PayMsgMapper;
import com.cn.zsc.db108.model.PayMsg;
import com.cn.zsc.db108.model.PayMsgExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;

@Service
public class OrderScheduler {

    @Resource
    private PayMsgMapper payMsgMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Scheduled(cron = "0/10 * * * * ?")
    public void orderNotify(){
        PayMsgExample payMsgExample = new PayMsgExample();
        payMsgExample.createCriteria().andStatusEqualTo(0);// 未发送
        List<PayMsg> payMsgs = payMsgMapper.selectByExample(payMsgExample);
        if(payMsgs != null && payMsgs.size() >0){
            for (PayMsg payMsg :payMsgs){
                Map<String, Object> param = new HashMap<>();
                param.put("orderId",payMsg.getOrderId());
                String forObject = restTemplate.getForObject("http://localhost:8080/handleOrder", String.class, param);
                if ("success".equals(forObject)){
                    // 更新消息表状态
                    payMsg.setStatus(1); // 发送成功
                }else {
                    // 更新失败次数
                    Integer failCnt = payMsg.getFailCnt();
                    failCnt++;
                    if (failCnt >5){
                        payMsg.setStatus(2);

                    }
                    payMsg.setFailCnt(failCnt);
                }
                payMsg.setUpdateTime(new Date());
                payMsg.setUpdateUser(0); // 系统更新
                payMsgMapper.updateByPrimaryKey(payMsg);
            }
        }
    }
}
